package com.example.starter.elasticsearch.configure;

import lombok.RequiredArgsConstructor;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

/**
 * @author 王令
 * @since 2023/9/14 14:43
 */
@RequiredArgsConstructor
@EnableConfigurationProperties(ElasticSearchProperties.class)
public class ElasticSearchConfiguration extends AbstractElasticsearchConfiguration {

    private final ElasticSearchProperties properties;

    @Bean
    @ConditionalOnMissingBean(RestHighLevelClient.class)
    @Override
    public RestHighLevelClient elasticsearchClient() {
        return RestClients.create(ClientConfiguration
                .builder()
                .connectedTo(properties.getHostAndPort())
                .build()
        ).rest();
    }

    @Bean
    @ConditionalOnMissingBean(ElasticsearchRestTemplate.class)
    public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient highLevelClient) {
        return new ElasticsearchRestTemplate(highLevelClient);
    }
}
